package com.testing.strclass;

public class StrStringBuild {

    public static void main(String[] args) throws Exception {
        strStringBuffer();
    }

    public static void strStringBuffer() throws Exception{
        // StringBuffer多线程下会出现安全的情况导致，打印出来的长度与实际预想的一致,如果不一致是因为线程还没执行完成
        StringBuffer stringBuffer = new StringBuffer();
        for (int i = 0; i < 10; i++) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    for (int j = 0; j < 1000 ; j++) {
                        stringBuffer.append("b");
                    }
                }
            },"test").start();
        }
        Thread.sleep(20);
        System.out.println(stringBuffer.length());
    }

    public static void strStringBuilder() throws Exception{
        // StringBuilder多线程下会出现不安全的情况导致，打印出来的长度与实际预想的不一致
        StringBuilder stringBuilder = new StringBuilder();
        for (int i = 0; i < 10; i++) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    for (int j = 0; j <1000 ; j++) {
                        stringBuilder.append("a");
                    }
                }
            },"test").start();
        }
        Thread.sleep(10);
        System.out.println(stringBuilder.length());
    }
}
